package com.rongke.web;


import com.alibaba.fastjson.JSONObject;
import com.rongke.alipayUtil.alipay.util.AlipayNotify;
import com.rongke.enums.FlowTypeEnum;
import com.rongke.enums.OrderStatusEnum;
import com.rongke.enums.PayTypeEnum;
import com.rongke.enums.UserTypeEnum;
import com.rongke.model.FlowDetail;
import com.rongke.model.Muser;
import com.rongke.model.Orders;
import com.rongke.service.*;
import com.rongke.wxPayUtil.util.WXpayCore;
import com.rongke.wxPayUtil.util.WXpayXmlUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 支付接口类
 * Created by bin on 2017/3/23.
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/money")
public class MoneyController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private MuserService muserService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private FlowDetailService flowDetailService;
    @Autowired
    private BuyTogetherGoodsService buyTogetherGoodsService;
    @Autowired
    private BuyTogetherUserService buyTogetherUserService;
    @Autowired
    private OrderGoodsService orderGoodsService;


    /**
     * 订单支付支付宝
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/alipay/orderSucc",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String orderSucc(HttpServletRequest request) throws UnsupportedEncodingException {
        log.debug("订单支付成功回调");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        if(AlipayNotify.verify(params)){//验证成功
            if(trade_status.equals("TRADE_FINISHED")){
//                log.error(params);
                alipyPaySucc(params);
            } else if (trade_status.equals("TRADE_SUCCESS")){
                alipyPaySucc(params);
                return "success";
            }

        }else{//验证失败
            log.debug("+++++++++++++++++++=验证失败");
            return "fail";
        }
        return "fail";
    }

    protected String alipyPaySucc(Map<String, String> params){
        String parmsStr=params.get("out_trade_no").split("a")[0];
        String total_fee = params.get("total_fee");
//        double money = Double.valueOf(total_fee);
        String isHead=null;
        Long orderId=null;
        orderId=Long.valueOf(parmsStr);
//    Long orderId= Long.valueOf(params.get("out_trade_no").split("a")[0]);
        Orders orders=ordersService.selectById(orderId);
        if (orders==null){
            return "success";
        }
        Long userId=orders.getMuserId();
        //如果不是带付款状态直接返回
        if(orders.getOrderStatus()!=OrderStatusEnum.WAIT_PAY.getType()){
            return "success";
        }
        //更新账单状态
        orders.setOutTradeNo(params.get("out_trade_no"));
        orders.setPayType(PayTypeEnum.ZHIFUBAO.getType());
        if(orders.getOrderType()==1){
            orders.setOrderStatus(OrderStatusEnum.BUYTOGETHER.getType());
        }else {
            orders.setOrderStatus(OrderStatusEnum.WAIT_SHIP.getType());
        }
        orders.setCashPayPrice(new BigDecimal(total_fee));
        orders.setPayDatetime(new Date());
        ordersService.updateById(orders);
        //消费总额刷新
        JSONObject jsonObject=ordersService.OrdersPay(orderId,PayTypeEnum.ZHIFUBAO.getType());
        if(orders.getOrderType()==1){
            isHead=params.get("out_trade_no").split("a")[1].substring(0,1);
        }
        // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为百夫长，则第一个百夫长不可用余额增加
        Muser recomendMuser=muserService.findFirstRecomendUser(userId, UserTypeEnum.CENTURION.getType());
        if(recomendMuser!=null){
            JSONObject jsonRecomend=accountService.updateRecomendUserAccount(recomendMuser.getId(),orderId);
            if("500".equals(jsonRecomend.getString("code"))){
                System.out.print(jsonRecomend.getString("message"));
            }
        }
        // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为千夫长，则第一个千夫长不可用余额增加
        Muser chiefCommander=muserService.findFirstRecomendUser(userId,UserTypeEnum.ChIEFCOMMANDER.getType());
        if(chiefCommander!=null){
            JSONObject jsonChief=accountService.updateRecomendUserAccount(chiefCommander.getId(),orderId);
            if("500".equals(jsonChief.getString("code"))){
                System.out.print(jsonChief.getString("message"));
            }
        }
        // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为加盟商，则第一个加盟商不可用余额增加
        Muser franchisee=muserService.findFirstRecomendUser(userId,UserTypeEnum.FRANCHISEE.getType());
        if(franchisee!=null){
            JSONObject jsonChief=accountService.updateRecomendUserAccount(franchisee.getId(),orderId);
            if("500".equals(jsonChief.getString("code"))){
                System.out.print(jsonChief.getString("message"));
            }
        }
        return "success";
    }


    /**
     * 订单支付微信
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/wxpay/orderSucc",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String orderwxSucc(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        outSteam.close();
        inStream.close();
        if (!WXpayCore.checkSign(params)) {
            // 支付失败
            return "fail";
        } else {
            System.out.println("===============付款成功==============");
            String total_fee = params.get("total_fee");
            double money = Double.valueOf(total_fee) / 100;
            String parmsStr=params.get("out_trade_no").split("a")[0];
            String isHead=null;
            Long orderId=null;
            orderId=Long.valueOf(parmsStr);
            Orders orders=ordersService.selectById(orderId);
            if(orders.getOrderType()==1){
                isHead=params.get("out_trade_no").split("a")[1].substring(0,1);
            }
            orders.setOutTradeNo(params.get("out_trade_no"));
            //更新账单状态
            if(orders.getOrderType()==1){
                orders.setOrderStatus(OrderStatusEnum.BUYTOGETHER.getType());
            }else {
                orders.setOrderStatus(OrderStatusEnum.WAIT_SHIP.getType());
            }
            orders.setPayType(PayTypeEnum.WEIXIN.getType());
            orders.setCashPayPrice(new BigDecimal(money));
            orders.setPayDatetime(new Date());
            ordersService.updateById(orders);
            //消费总额刷新
            JSONObject jsonObject=ordersService.OrdersPay(orderId,PayTypeEnum.WEIXIN.getType());

            Long userId=orders.getMuserId();
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为百夫长，则第一个百夫长不可用余额增加
            Muser recomendMuser=muserService.findFirstRecomendUser(userId, UserTypeEnum.CENTURION.getType());
            if(recomendMuser!=null){
                JSONObject jsonRecomend=accountService.updateRecomendUserAccount(recomendMuser.getId(),orderId);
                if("500".equals(jsonRecomend.getString("code"))){
                    System.out.print(jsonRecomend.getString("message"));
                }
            }
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为千夫长，则第一个千夫长不可用余额增加
            Muser chiefCommander=muserService.findFirstRecomendUser(userId,UserTypeEnum.ChIEFCOMMANDER.getType());
            if(chiefCommander!=null){
                JSONObject jsonChief=accountService.updateRecomendUserAccount(chiefCommander.getId(),orderId);
                if("500".equals(jsonChief.getString("code"))){
                    System.out.print(jsonChief.getString("message"));
                }
            }
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为加盟商，则第一个加盟商不可用余额增加
            Muser franchisee=muserService.findFirstRecomendUser(userId,UserTypeEnum.FRANCHISEE.getType());
            if(franchisee!=null){
                JSONObject jsonChief=accountService.updateRecomendUserAccount(franchisee.getId(),orderId);
                if("500".equals(jsonChief.getString("code"))){
                    System.out.print(jsonChief.getString("message"));
                }
            }

            // 处理业务完毕
            // ------------------------------
            return "success";
        }
    }

    public  static  void main(String str[]){
        String str2="54545|212";
        System.out.print(UUID.randomUUID().toString().replaceAll("-", "").toLowerCase());
    }

    /**
     * 彩虹会员注册 微信支付
     * @param request
     * @return
     * @throws IOException
     */

    @RequestMapping(value = "/wxpay/registerSucc",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String registerSucc(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        outSteam.close();
        inStream.close();
        if (!WXpayCore.checkSign(params)) {
            // 支付失败
            return "fail";
        } else {
            System.out.println("===============付款成功==============");
            String total_fee = params.get("total_fee");
            double money = Double.valueOf(total_fee) / 100;
            Long userId = Long.valueOf(params.get("out_trade_no").split("a")[0]);
            Muser muser=muserService.selectById(userId);
            muser.setMemberType(2);
            muserService.updateById(muser);

            FlowDetail fd=new FlowDetail();
            fd.setMoney(new BigDecimal(money));
            fd.setFlowType(FlowTypeEnum.ORDER.getType());
            fd.setMuserId(userId);
            fd.setGmtDatetime(new Date());
            fd.setTitle("注册彩虹会员微信支付");
            flowDetailService.insert(fd);
            return "success";
        }



    }
    /**
     * 彩虹会员注册 支付宝支付
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/alipay/registerSucc",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String registerWXSucc(HttpServletRequest request) throws UnsupportedEncodingException {
        log.debug("订单支付成功回调");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        if(AlipayNotify.verify(params)){//验证成功
            if(trade_status.equals("TRADE_FINISHED")){
            } else if (trade_status.equals("TRADE_SUCCESS")){
                String money = params.get("total_fee");
                Long userId = Long.valueOf(params.get("out_trade_no").split("a")[0]);
                Muser muser=muserService.selectById(userId);
                muser.setMemberType(2);
                //将注册时间改为当前时间，不管是升级彩虹的还是一开始就注册彩虹会员的
                muser.setGmtDatetime(new Date());
                muserService.updateById(muser);

                FlowDetail fd=new FlowDetail();
                fd.setMoney(new BigDecimal(money));
                fd.setFlowType(FlowTypeEnum.ORDER.getType());
                fd.setMuserId(userId);
                fd.setTitle("注册彩虹会员支付宝支付");
                flowDetailService.insert(fd);
                return "success";
            }

        }else{//验证失败
            log.debug("+++++++++++++++++++=验证失败");
            return "fail";
        }
        return "fail";
    }






}



